﻿using log4net.Appender;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlaceOrder_Core.Helper
{
    public class AppLog
    {
        private static string filepath = AppDomain.CurrentDomain.BaseDirectory + @"\全益订单服务程序日志\";

        private static readonly log4net.ILog logComm = log4net.LogManager.GetLogger("AppLog");


        /// <summary>
        /// 清理保留最近15天的日志文件，删除其他旧的日志文件
        /// </summary>
        public static void CleanupOldLogs()
        {
            lock (o)
            {
                try
                {
                    // 获取当前日期
                    DateTime currentDate = DateTime.Now;

                    // 遍历所有日志目录
                    foreach (var yearFolder in Directory.GetDirectories(filepath))
                    {
                        foreach (var monthFolder in Directory.GetDirectories(yearFolder))
                        {
                            // 遍历所有日志文件
                            foreach (var file in Directory.GetFiles(monthFolder))
                            {
                                try
                                {
                                    // 获取文件的创建日期
                                    DateTime fileCreationDate = File.GetLastWriteTime(file);

                                    // 如果文件日期早于7天前，则删除
                                    if (fileCreationDate < currentDate.AddDays(-7))
                                    {
                                        File.Delete(file);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    // 记录异常或处理文件删除异常
                                    AppLog.WriteError($"Failed to delete file {file}: {ex.Message}");
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // 记录异常或处理目录遍历异常
                    AppLog.WriteError($"Failed to clean up old logs: {ex.Message}");
                }
            }
        }

        static AppLog()
        {
            log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));

            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }
        }
        public static readonly object o = new object();
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="isWrite">是否写</param>
        /// <param name="action">写日志的方法</param>
        /// <param name="info">日志文件名，便于分开日志文件</param>
        private static void WriteLog(string msg, bool isWrite, Action<object> action, string info = "")
        {
            if (isWrite)
            {
                lock (o)
                {
                    // 构建日志文件路径
                    string currentDate = DateTime.Now.ToString("yyyy-MM-dd");
                    string yearFolder = Path.Combine(filepath, DateTime.Now.ToString("yyyy"));
                    string monthFolder = Path.Combine(yearFolder, DateTime.Now.ToString("MM"));
                    //string filename = $"全益订单服务系统_{action.Method.Name}_{info}_{currentDate}.log";
                    string filename = $"实盘下单_{currentDate}.log";
                    string fullFilePath = Path.Combine(monthFolder, filename);

                    // 确保年月文件夹存在
                    if (!Directory.Exists(yearFolder))
                    {
                        Directory.CreateDirectory(yearFolder);
                    }
                    if (!Directory.Exists(monthFolder))
                    {
                        Directory.CreateDirectory(monthFolder);
                    }

                    // 更改日志文件路径
                    var repository = LogManager.GetRepository();
                    var appenders = repository.GetAppenders();
                    if (appenders.Length > 0)
                    {
                        RollingFileAppender targetApder = null;
                        foreach (var Apder in appenders)
                        {
                            if (Apder.Name == "AppLog")
                            {
                                targetApder = Apder as RollingFileAppender;
                                break;
                            }
                        }
                        if (targetApder?.Name == "AppLog")//如果是文件输出类型日志，则更改输出路径
                        {
                            if (!targetApder.File.Contains(filename))
                            {
                                targetApder.File = fullFilePath;
                                targetApder.ActivateOptions();
                            }
                        }
                    }

                    // 写入日志
                    action(msg);
                }
            }
        }


        //private static void WriteLog(string msg, bool isWrite, Action<object> action, string info = "")
        //{
        //    if (isWrite)
        //    {
        //        lock (o)
        //        {
        //            string filename = $"AppLog_{action.Method.Name}_{info}_{DateTime.Now.ToString("yyyyMMdd_HH")}.log";
        //            var repository = LogManager.GetRepository();

        //            #region MyRegion
        //            var appenders = repository.GetAppenders();
        //            if (appenders.Length > 0)
        //            {
        //                RollingFileAppender targetApder = null;
        //                foreach (var Apder in appenders)
        //                {
        //                    if (Apder.Name == "AppLog")
        //                    {
        //                        targetApder = Apder as RollingFileAppender;
        //                        break;
        //                    }
        //                }
        //                if (targetApder.Name == "AppLog")//如果是文件输出类型日志，则更改输出路径
        //                {
        //                    if (targetApder != null)
        //                    {
        //                        if (!targetApder.File.Contains(filename))
        //                        {
        //                            targetApder.File = @"全益订单服务程序日志\" + filename;
        //                            targetApder.ActivateOptions();
        //                        }
        //                    }
        //                }
        //            }
        //            #endregion
        //            action(msg);
        //            //logComm.Error(msg + "\n");
        //        }
        //    }
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="info">日志文件名，便于分开日志文件</param>
        /// <param name="isWrite">是否写入</param>
        public static void WriteError(string msg, string info = "", bool isWrite = true)
        {
            WriteLog(msg, isWrite, logComm.Error, info);
        }
        public static void WriteInfo(string msg, string info = "", bool isWrite = true)
        {
            WriteLog(msg, isWrite, logComm.Info, info);
        }
        public static void WriteWarn(string msg, string info = "", bool isWrite = true)
        {
            WriteLog(msg, isWrite, logComm.Warn, info);
        }
        public static void WriteFatal(string msg, string info = "", bool isWrite = true)
        {
            WriteLog(msg, isWrite, logComm.Fatal, info);
        }
    }
}
